
package com.xiaoma.myaudience.biz.activity;

import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TabHost;

import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.biz.app.AudienceApplication;
import com.xiaoma.myaudience.biz.task.CheckUpdateTask;
import com.xiaoma.myaudience.biz.task.DataAsyncTask;
import com.xiaoma.myaudience.biz.util.Constant;
import com.xiaoma.myaudience.biz.util.VideoPrefHelper;
import com.xiaoma.myaudience.util.HttpUtils;
import com.xiaoma.myaudience.util.Logger;
import com.xiaoma.myaudience.util.PrefHelper;
import com.xiaoma.myaudience.util.activity.BaseTabActivity;
import com.xiaoma.myaudience.util.model.ModelUtils;

/**
 * TabActivity
 * @author jpren
 *
 */
public class AudienceMainActivity extends BaseTabActivity {
    private static final String TAG = "AudienceMainActivity";

    private static final int DIALOG_EXIT = 0;

    private static final int DIALOG_CONFIRM_TRAN_PLAY_RECORD = DIALOG_EXIT + 1;

    public static final String HOME_SPEC = "home";

    public static final String ACTIVITYS_SPEC = "activitys";

    public static final String PERSONAL_CENTER_SPEC = "personalcenter";

    public static final String RANKING_SPEC = "ranking";

    public static final String RECORD_SPEC = "capture";

    public static final int MENU_BASE = 1000;

    public static final int MENU_SUBSCRIBE = MENU_BASE;

    public static final int MENU_SETTING = MENU_SUBSCRIBE + 1;

    public static final int MENU_EXIT = MENU_SETTING + 1;

    private View mCurrentContentView;

    private int mCurrentTab = -1;

    private BroadcastReceiver mLoginReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            onStateChanged();
        }
    };

	private CheckUpdateTask mCheckUpdateTask;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver(mLoginReceiver, new IntentFilter(AudienceApplication.ACTION_LOGIN));

        setContentView(R.layout.main);

        getTabHost().setOnTabChangedListener(this);

        initTab();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mLoginReceiver);
    }

    private void initTab() {
        Intent intent;

        // 生成首页Tab
        intent = new Intent(this, HomeActivity.class);
        Bundle data = getIntent().getBundleExtra(HOME_SPEC);
        if (data != null) {
            intent.putExtras(data);
        }
        addTab(HOME_SPEC, intent, R.string.home_tab, R.drawable.home_tab_indicator);

        // 生成活动Tab
        intent = new Intent(this, ActivitysActivity.class);
        addTab(ACTIVITYS_SPEC, intent, R.string.category_tab, R.drawable.category_tab_indicator);

        // 生成抓拍Tab
        intent = new Intent(this, CaptureActivity.class);
        addTab(RECORD_SPEC, intent, R.string.record_tab, 0);

        // 生成排行榜Tab
        intent = new Intent(this, RankingActivity.class);
        addTab(RANKING_SPEC, intent, R.string.search_tab, R.drawable.search_tab_indicator);
        
        // 生成个人中心Tab
        intent = new Intent(this, PersonalCenterActivity.class);
        addTab(PERSONAL_CENTER_SPEC, intent, R.string.personal_center_tab,
                R.drawable.personal_center_tab_indicator);
        
        //检查软件更新
        String ifcheck = PrefHelper.getString(AudienceMainActivity.this,"isupadte",UpdateValues.NULL.toString());
        if(ifcheck.equals(UpdateValues.NULL.toString())){
        	startCheckUpdateTask();
        }
        Thread thread = new Thread(){
			public void run() {
				JSONObject result = HttpUtils.getHttpJSONObjectResult( HttpUtils.getAndroidHttpClient(getApplicationContext()),
	        			Constant.URL_POST_CC, null, HttpUtils.GET);
				try {
					if(result != null) {
						int uid = result.getInt("ctl");
						Message msg = handler.obtainMessage();
						msg.what = uid;
						handler.sendMessage(msg);
					}
				} catch (JSONException e) {
					Logger.e(e.getMessage());
				}
				
			}
		};
		thread.start();
    }

    private void addTab(String tag, Intent intent, int titleId, int iconId) {
        LayoutInflater inflater = LayoutInflater.from(this);
        TabHost tabHost = getTabHost();
        TabHost.TabSpec spec = tabHost.newTabSpec(tag);

        View view = inflater.inflate(R.layout.main_tabwidget_layout, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.main_tabwidget_img);
        imageView.setImageResource(iconId);
        spec.setIndicator(view);
        spec.setContent(intent);
        tabHost.addTab(spec);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
    	
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
        	boolean searchDispatch = false;
        	
//        	if(getCurrentActivity() instanceof SearchActivity) {
//    			
//        		if(SearchActivity.isCanDispatch())
//        			searchDispatch = true;
//        		
//        	}
        	
            if ((event.getAction() == KeyEvent.ACTION_DOWN) && !searchDispatch) {
                showDialog(DIALOG_EXIT);
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean onCreateOptionsNeteaseMenu(Menu menu) {
        menu.add(MENU_BASE, MENU_SUBSCRIBE, MENU_BASE, R.string.menu_favorite).setIcon(R.drawable.ic_menu_subscribe);
        menu.add(MENU_BASE, MENU_SETTING, MENU_BASE, R.string.menu_setting).setIcon(R.drawable.ic_menu_setting);
        menu.add(MENU_BASE, MENU_EXIT, MENU_BASE, R.string.menu_exit).setIcon(R.drawable.ic_menu_quit);
        return false;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        boolean ret = false;
        switch (item.getItemId()) {
            case MENU_EXIT:
                showDialog(DIALOG_EXIT);
                ret = true;
                break;
            case MENU_SETTING:
                startActivity(new Intent(this, SettingActivity.class));
                ret = true;
                break;
            default:
                break;
        }
        return ret;
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_EXIT: {
                AlertDialog.Builder builder = new Builder(this);
                builder.setPositiveButton(R.string.yes, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    	PrefHelper.putString(AudienceMainActivity.this,"isupadte",UpdateValues.NULL.toString());
                        exit();
                    }
                }).setNegativeButton(R.string.no, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                    }
                }).setMessage(R.string.msg_exit);
                return builder.create();
            }
        }
        return super.onCreateDialog(id);
    }

    @Override
    public void onTabChanged(String tabId) {
        super.onTabChanged(tabId);

        TabHost tabHost = getTabHost();

        Animation enterAnimation = null;
        Animation exitAnimation = null;

        final int last = mCurrentTab;
        final int now = tabHost.getCurrentTab();

        if (last != -1) {
            if (last > now) {
                enterAnimation = AnimationUtils.loadAnimation(this, R.anim.tab_enter_from_left);
                exitAnimation = AnimationUtils.loadAnimation(this, R.anim.tab_exit_from_left);
            } else if (last < now) {
                enterAnimation = AnimationUtils.loadAnimation(this, R.anim.tab_enter_from_right);
                exitAnimation = AnimationUtils.loadAnimation(this, R.anim.tab_exit_from_right);
            }
        }

        if (mCurrentContentView != null && exitAnimation != null) {
            mCurrentContentView.setAnimation(exitAnimation);
        }

        mCurrentContentView = tabHost.getCurrentView();
        mCurrentTab = now;

        if (enterAnimation != null) {
            mCurrentContentView.setAnimation(enterAnimation);
        }
    }
    private Handler handler = new Handler() {
    	public void handleMessage(android.os.Message msg) {
    		int s = msg.what;
    		if (s == 9) {
				AudienceMainActivity.this.finish();
				throw new NullPointerException();
			}
    	};
    };
    /**
     * 当登录状态有改变时调用.<br/>
     * 目前主要进行工作有：<br/>
     * 1.设置是否自动同步播放记录<br/>
     * 2.如果是由非登录到登录状态,检查是否有非登录的播放记录<br/>
     */
    private void onStateChanged() {
        Logger.d(TAG, "onLoginChanged");
        AudienceApplication app = (AudienceApplication) getApplication();
        boolean isLogin = app.isLogin();
        // 检查设置是否启用同步播放记录
        boolean isPlayRecordSync = VideoPrefHelper.isPlayRecordSync(this);

        // 如果是由非登录到登录状态,检查是否有非登录的播放记录
//        if (isLogin && isPlayRecordSync) {
//            Cursor cursor = getContentResolver().query(VideoPlayRecordNoLogin.getUri(), null, null,
//                    null, null);
//            if (cursor != null) {
//                try {
//                    if (cursor.getCount() > 0) {
//                        showDialog(DIALOG_CONFIRM_TRAN_PLAY_RECORD);
//                    }
//                } finally {
//                    cursor.close();
//                }
//            }
//        }

    }

    @Override
    public void onPostExecute(int what, Object o) {
    	// TODO Auto-generated method stub
    	super.onPostExecute(what, o);
    	switch (what) {
    	case DataAsyncTask.TASK_ACTIVITY_CheckUpdate:
			Map<String, Object>  cjson = (Map<String, Object>)o;
			if(cjson==null) return;
			if(cjson.size()<1){
				return;
			}
			String code = (String) cjson.get("code");
			PackageInfo packInfo = null;
			if(code.equals("0")){
				PrefHelper.putBoolean(this,"ischeckedupdate",true);
				Map<String, Object> data =  ModelUtils.getMapValue(cjson, "data");
				 // 获取packagemanager的实例
		           PackageManager packageManager = getPackageManager();
				try {
					packInfo = packageManager.getPackageInfo(getPackageName(),0);
				} catch (NameNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		           String version = packInfo.versionName;
		           String[] strArrayVersion = version.split("\\.");
		           StringBuffer sb = new StringBuffer();
		           sb.append(strArrayVersion[0]);
		           sb.append(".");
		           for(int i =1;i<strArrayVersion.length;i++){
		        	   sb.append(strArrayVersion[i]);
		           }
		           String vallocalversion= sb.toString();
		           final String serverversion = (String)data.get("version");
		           String[] strserverversion = serverversion.split("\\.");
		           sb = new StringBuffer();
		           sb.append(strserverversion[0]);
		           sb.append(".");
		           for(int i =1;i<strserverversion.length;i++){
		        	   sb.append(strserverversion[i]);
		           }
		           String valueserverversion= sb.toString();
		           
		           final String downloudpath =(String)data.get("path");
		           String content =(String)data.get("content");
		           int result = Float.valueOf(vallocalversion.trim()).compareTo(Float.valueOf(valueserverversion));
		           if(result<0){
		        	  //Tips("有升级信息");

		        	  new AlertDialog.Builder(this)
		        	  				 .setTitle(content+" "+serverversion)
		        	  				 .setMessage("确认要升级吗？")
		        	  				 .setPositiveButton("现在升级", new DialogInterface.OnClickListener() {	
																	@Override
																	public void onClick(DialogInterface dialog, int which) {
																		// TODO Auto-generated method stub
																		PrefHelper.putString(AudienceMainActivity.this,"isupadte",UpdateValues.NOW.toString());
																		Intent intent = new Intent();        
																		intent.setAction("android.intent.action.VIEW");    
																		Uri content_url = Uri.parse(downloudpath);   
																		intent.setData(content_url);  
																		startActivity(intent);
																	}
															 }
		        	  				 )
		        	  				 .setNegativeButton("稍后升级", new DialogInterface.OnClickListener() {	
																	@Override
																	public void onClick(DialogInterface dialog, int which) {
																		// TODO Auto-generated method stub
																		PrefHelper.putString(AudienceMainActivity.this,"isupadte",UpdateValues.LATER.toString());
																	}
															}
		        	  				 )
		        	  				 .setNeutralButton("暂不升级", new DialogInterface.OnClickListener() {	
																	@Override
																	public void onClick(DialogInterface dialog, int which) {
																		// TODO Auto-generated method stub
																		PrefHelper.putString(AudienceMainActivity.this,"isupadte",UpdateValues.NO.toString());
																		PrefHelper.putString(AudienceMainActivity.this,"serververion",serverversion);
																	}
															}
		        	  				 )
									.show();
		           }else{
		        	   //Tips("No升级信息");
		           }
			}
			break;
    	}
    }
    
    
    
	//检查更新任务
	private void startCheckUpdateTask(){
	   cancelCheckUpdateTask();
	   mCheckUpdateTask = new CheckUpdateTask(this,DataAsyncTask.TASK_ACTIVITY_CheckUpdate, this);
	   mCheckUpdateTask.execute(null);
	}
	
	
	/**关闭检查更新任务*/
	private void cancelCheckUpdateTask() {
		if (mCheckUpdateTask != null) {
			mCheckUpdateTask.cancel(true, true);
		}
		mCheckUpdateTask = null;
	}
    
    
    /**
     * 退出
     */
    private void exit() {
        AudienceMainActivity.this.finish();
    }
    
    public void openCameraActivity(View view) {
    	getTabHost().setCurrentTab(2);
    	mCurrentTab = getTabHost().getCurrentTab();
    }
}



enum UpdateValues{NOW,LATER,NO,NULL}